package com.ht.shop.listeners;

import com.ht.shop.cache.GoodTypeCache;
import com.ht.shop.pojo.TbGoodsType;
import com.ht.shop.service.GoodsTypeService;
import com.ht.shop.service.impl.GoodsTypeServiceImpl;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.SQLException;
import java.util.List;

@WebListener
public class LoadTypeCacheContextListener implements ServletContextListener {

    private GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();

    @Override
    public void contextInitialized(ServletContextEvent sce) {


        try {
            System.out.println("加载缓存分类");
            List<TbGoodsType> goodsTypeList = goodsTypeService.findAllSecondLevelType();
            GoodTypeCache.setAllSecondTypes(goodsTypeList);
            sce.getServletContext().setAttribute("goodsTypeList",GoodTypeCache.getAllSecondTypes());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        GoodTypeCache.clearCache();
    }
}
